package ecnu.ecgbackend.config.security.service;

import ecnu.ecgbackend.entity.User;
import ecnu.ecgbackend.service.DiagnosisUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;

@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    DiagnosisUserService diagnosisUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user= diagnosisUserService.findUserByUserName(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        user.setAuthorities((new ArrayList<String>(Collections.singletonList(user.getRole()))).stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        return user;
    }
}
